package bar.dark.lee.cashdrawing;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.setting.auto.AutoInsertActivity;
import bar.dark.lee.setting.mybankauto.MyBankAutoActivity;
import bar.dark.lee.setting.mybankauto.MyBankAutoData;

public class InsertMyBankActivity extends SuperActivity
{
	public static final int REQUEST_OUT_BANK = 0;
	public static final int REQUEST_OUT_CREDIT = 2;
	public static final int REQUEST_IN_BANK = 3;
	public static final int REQUEST_OUT_CATEGORY = 4;
	public static final int REQUEST_IN_CATEGORY = 5;
	public static final int REQUEST_AUTO_DATE = 6;
	
	private View helpView;
	
	/** 통장 라디오 버튼 */
	private RadioButton bankRadio;
	/** 신용카드 라디오 버튼 */
	private RadioButton creditRadio;
	
	/** 출금 통장 뷰 */
	private View myBankView;
	/** 출금 통장 텍스트 뷰 */
	private TextView myBankTextView;
	
	/** 출금 신용카드 뷰 */
	private View myCreditView;
	/** 출금 신용카드 텍스트 뷰 */
	private TextView myCreditTextView;
	
	/** 출금 타이틀 */
	private TextView outBalanceTitle;
	/** 출금  잔액 */
	private TextView outBalanceTextView;
	
	/** 입금 통장 뷰 */
	private View myBankInView;
	/** 입금 통장 텍스트 뷰 */
	private TextView myBankInTextView;
	
	/** 입금  잔액 */
	private TextView inBalanceTextView;
	
	/** 이체 금액 */
	private EditText money;
	
	/** 날짜 뷰 */
	private View dateView;
	/** 날짜 텍스트 뷰 */
	private TextView dateTextView;
	
//	/** 지출 카테고리 뷰 */
//	private View categoryOutView;
//	/** 지출 카테고리 텍스트 뷰 */
//	private TextView categoryOutTextView;
	
	/** 수입 카테고리 뷰 */
	private View categoryInView;
	/** 수입 카테고리 텍스트 뷰 */
	private TextView categoryInTextView;
	
	/** 수수료 */
	private EditText susuMoney;
	
	/** 메모 뷰 */
	private View memoView;
	/** 메모 텍스트 뷰 */
	private EditText memoEditText;
	
	/** 입력 버튼 */
	private Button insertButton;
	
	/** 이체이름 뷰 */
	private View autoName;
	/** 이체 이름 에티트 텍스트 뷰 */
	private EditText autoNameEditText;
	
	private DBSQLite sql;
	
	private ArrayList<String> outBankList = new ArrayList<String>();
	private ArrayList<String> outCreditList = new ArrayList<String>();
	private ArrayList<String> inBankList = new ArrayList<String>();
	
	private ArrayList<String> categoryOutList =  new ArrayList<String>();
	private ArrayList<String> categoryInList =  new ArrayList<String>();
	
	private ArrayList<String> dateList = new ArrayList<String>();
	
	private int toYear;
	private int toMonth;
	private int toDay;

	private int linkId = -1;
	private int inoutLinkId = -1;
	
	private int flag = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		isAdFlag = false;
		
		super.onCreate(savedInstanceState);
		
		Intent intent = getIntent();
		
		flag = intent.getIntExtra(MyBankAutoActivity.AUTO_UPDATE_INSERT_FLAG, -1);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.insert_mybank);
		
		setFindView();
		
		if (flag == 1)
		{
			setTitle("내통장 이체 입력");
			autoName.setVisibility(View.VISIBLE);
			helpView.setVisibility(View.GONE);
		}
		else if (flag == 0)
		{
			setTitle("내통장 이체 수정");
			autoName.setVisibility(View.VISIBLE);
			helpView.setVisibility(View.GONE);
		}
		else 
		{
			setGoneTitle();
			autoName.setVisibility(View.GONE);
		}
		
		setOnClickListener();
		setData();
	}

	private void setFindView()
	{
		helpView = findViewById(R.id.insertMyBankHelp);
		
		 bankRadio = (RadioButton) findViewById(R.id.insertMyBankRadio);
		 creditRadio = (RadioButton) findViewById(R.id.insertMyCreditRadio);
		
		 myBankView = findViewById(R.id.insertMyBankView);
		 myBankTextView = (TextView) findViewById(R.id.insertMyBankKind);
		
		 myCreditView = findViewById(R.id.insertMyCreditView);
		 myCreditTextView = (TextView) findViewById(R.id.insertMyCreditKind);
		
		 outBalanceTitle = (TextView) findViewById(R.id.insertMyBankBalanceTitle);
		 outBalanceTextView = (TextView) findViewById(R.id.insertMyBankOutBalance);
		
		 money = (EditText) findViewById(R.id.insertMyBankMoney);
		 EditTextInputFilter.filteringMoneyEditText(money);
		
		 myBankInView = findViewById(R.id.insertMyBankInView);
		 myBankInTextView = (TextView) findViewById(R.id.insertMyBankInTextView);
		
		 inBalanceTextView = (TextView) findViewById(R.id.insertMyBankInBalance);
		
		 dateView = findViewById(R.id.insertMyBankDate);
		 dateTextView = (TextView) findViewById(R.id.insertMyBankDateTextView);
		
//		 categoryOutView = findViewById(R.id.insertMyBankOutCategory);
//		 categoryOutTextView = (TextView) findViewById(R.id.insertMyBankOutCategoryTextView);
		 
		 categoryInView = findViewById(R.id.insertMyBankInCategory);
		 categoryInTextView = (TextView) findViewById(R.id.insertMyBankInCategoryTextView);
		
		 susuMoney = (EditText) findViewById(R.id.insertMyBankSusuMoney);
		 EditTextInputFilter.filteringMoneyEditText(susuMoney);
		 
		 memoView = findViewById(R.id.insertMyBankMemoView);
		 memoEditText = (EditText) findViewById(R.id.insertMyBankMemo);
		 
		 insertButton = (Button) findViewById(R.id.insertMyBankInsertButton);
		 
		 autoName = findViewById(R.id.insertMyBankNameView);
		 autoNameEditText = (EditText) findViewById(R.id.insertMyBankName);
	}
	
	private void setOnClickListener()
	{
		bankRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				myCreditView.setVisibility(View.GONE);
				
				myBankView.setVisibility(View.VISIBLE);
				
				bankRadio.setChecked(true);
				creditRadio.setChecked(false);
				
				setBalanceOutBank();
				setFilterBankData();
				setBalanceInBank();
			}
		});
		
		creditRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				myBankView.setVisibility(View.GONE);
				
				myCreditView.setVisibility(View.VISIBLE);
				
				bankRadio.setChecked(false);
				creditRadio.setChecked(true);
				
				setBalanceCredit();
				setFilterCreditData();
				setBalanceInBank();
			}
		});
		
		myBankView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertMyBankActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, outBankList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, myBankTextView.getText().toString());
				startActivityForResult(intent, REQUEST_OUT_BANK);
			}
		});
		
		myCreditView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertMyBankActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, outCreditList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, myCreditTextView.getText().toString());
				startActivityForResult(intent, REQUEST_OUT_CREDIT);
			}
		});
		
		myBankInView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertMyBankActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, inBankList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, myBankInTextView.getText().toString());
				startActivityForResult(intent, REQUEST_IN_BANK);
			}
		});
		
//		categoryOutView.setOnClickListener(new OnClickListener()
//		{
//			@Override
//			public void onClick(View v)
//			{
//				Intent intent = new Intent(InsertMyBankActivity.this, RadioDialogActivity.class);
//				intent.putExtra(RadioDialogActivity.RADIODATA, categoryOutList);
//				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryOutTextView.getText().toString());
//				intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_MOVE_TYPE);
//				intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_MOVE_TYPE_STRING);
//				startActivityForResult(intent, REQUEST_OUT_CATEGORY);
//			}
//		});
		
		categoryInView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(InsertMyBankActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, categoryInList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryInTextView.getText().toString());
				intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_MOVE_TYPE);
				intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_MOVE_TYPE_STRING);
				startActivityForResult(intent, REQUEST_IN_CATEGORY);
			}
		});
		
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (flag > -1)
				{
//					Intent intent = new Intent(InsertMyBankActivity.this, RadioDialogActivity.class);
//					intent.putExtra(RadioDialogActivity.RADIODATA, dateList);
//					intent.putExtra(RadioDialogActivity.RADIOSELECT, dateTextView.getText().toString());
//					startActivityForResult(intent, REQUEST_AUTO_DATE);
					
					CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
						@Override
						public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
							
							dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
							
							toYear = year;
							toMonth = monthOfYear;
							toDay = dayOfMonth;
						}
					}, toYear, toMonth, toDay);
					
					cpd.show();
				}
				else
				{
					CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
						@Override
						public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
							
							dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
							
							toYear = year;
							toMonth = monthOfYear;
							toDay = dayOfMonth;
						}
					}, toYear, toMonth, toDay);
					
					cpd.show();
				}
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (money.length() < 1 || money.length() < 1)
				{
					BDUtil.showDialog(InsertMyBankActivity.this, "금액오류", "금액을 정확히 입력해주세요.");
					return;
				}
				
				if (bankRadio.isChecked())
				{
					if ((Boolean) myBankView.getTag() == false)
					{
						BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
						return;
					}
				}
				else if (creditRadio.isChecked())
				{
					if ((Boolean) myCreditView.getTag() == false)
					{
						BDUtil.showDialogManager(superContext, "신용카드가 하나도 없습니다.");
						return;
					}
				}
				
				if ((Boolean) myBankInView.getTag() == false)
				{
					BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
					return;
				}
				
				if (flag == 0 || flag == 1)
				{
					if (autoNameEditText.getText().toString().equals(""))
					{
						BDUtil.showDialog(InsertMyBankActivity.this, "이름오류", "이체 이름을 입력해주세요.");
						return;
					}
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag);
			}
		});
	}
	
	private void setData()
	{
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
		toMonth = cal.get(Calendar.MONTH);
		toDay = cal.get(Calendar.DAY_OF_MONTH);
		
		dateTextView.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
		
		for (int i = 0; i < 30; i++)
		{
			String date = "" + (i + 1);
			dateList.add(date);
		}
		
//		sql.selectMapTile(this, "SELECT kind FROM category_move_list ORDER BY count DESC", new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				categoryOutList = new ArrayList<String>();
//				
//				int nameIndex = c.getColumnIndex("kind");
//				c.moveToFirst();
//				
//				for (int i = 0; i < c.getCount(); i++)
//				{
//					String kind = c.getString(nameIndex);
//					categoryOutList.add(kind);
//					c.moveToNext();
//				}
//				
//				if (categoryOutList.size() < 1)
//				{
//					String memo = "없음";
//					categoryOutList.add(memo);
//					categoryOutView.setClickable(false);
//				}
//				
//				categoryOutTextView.setText(categoryOutList.get(0).toString());
//			}
//		});
		
		sql.selectMapTile(this, "SELECT kind FROM category_move_list ORDER BY count DESC", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				categoryInList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("kind");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					categoryInList.add(kind);
					c.moveToNext();
				}
				
				if (categoryInList.size() < 1)
				{
					String memo = "없음";
					categoryInList.add(memo);
					categoryInView.setClickable(false);
				}
				
				categoryInTextView.setText(categoryInList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				outBankList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					outBankList.add(kind);
					c.moveToNext();
				}
				
				if (outBankList.size() < 1)
				{
					String memo = "없음";
					outBankList.add(memo);
					myBankView.setClickable(false);
					myBankView.setTag(false);
				}
				else
				{
					myBankView.setClickable(true);
					myBankView.setTag(true);
				}
				
				myBankTextView.setText(outBankList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				outCreditList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					outCreditList.add(kind);
					c.moveToNext();
				}
				
				if (outCreditList.size() < 1)
				{
					String memo = "없음";
					outCreditList.add(memo);
					myCreditView.setClickable(false);
					myCreditView.setTag(false);
				}
				else
				{
					myCreditView.setClickable(true);
					myCreditView.setTag(true);
				}
				
				myCreditTextView.setText(outCreditList.get(0).toString());
			}
		});
		
		setFilterBankData();
		setBalanceInBank();
		setBalanceOutBank();
		
		if (flag == 1)
		{
//			dateTextView.setText(toDay + "");
			
			insertButton.setText("입력");
		}
		else if (flag == 0)
		{
			setUpdateData();
			
			insertButton.setText("수정");
		}
	}
	
	private void setUpdateData()
	{
		Intent intent = getIntent();
		
		MyBankAutoData data = intent.getParcelableExtra(MyBankAutoActivity.AUTO_DATA);
		
		autoNameEditText.setText(data.getName());
		
		if (data.getKind().equals("1"))
		{
			bankRadio.setChecked(true);
			creditRadio.setChecked(false);
			myBankView.setVisibility(View.VISIBLE);
			myCreditView.setVisibility(View.GONE);
			myBankTextView.setText(data.getOutkind());
			setBalanceOutBank();
		}
		else if (data.getKind().equals("2"))
		{
			bankRadio.setChecked(false);
			creditRadio.setChecked(true);
			myBankView.setVisibility(View.GONE);
			myCreditView.setVisibility(View.VISIBLE);
			myCreditTextView.setText(data.getOutkind());
			setBalanceCredit();
		}
		
//		categoryOutTextView.setText(data.getOutCategory());
		
		myBankInTextView.setText(data.getInkind());
		setBalanceInBank();
		categoryInTextView.setText(data.getInCategory());
		
		money.setText(data.getMoney());
		
		String date = data.getSigndate();
		
		if (date.length() < 3)
		{
			dateTextView.setText(BDUtil.getDate(toYear, toMonth, Integer.parseInt(data.getAutodate())));
		}
		else
		{
			int [] dates = BDUtil.getDateSet(date);
			
			Calendar cal = Calendar.getInstance();
			cal.set(dates[0], dates[1], dates[2]);
			cal.add(Calendar.MONTH, 1);
			
			dateTextView.setText(BDUtil.getDate(
					cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), Integer.parseInt(data.getAutodate())));
		}
		
//		dateTextView.setText(data.getAutodate());
		susuMoney.setText(data.getSusuMoney());
		
		if (data.getMemo() != null && data.getMemo().length() > 0)
		{
			memoView.setVisibility(View.VISIBLE);
			memoEditText.setText(data.getMemo());
		}
	}

	private void setFilterBankData()
	{
		inBankList.clear();
		
		for (int i = 0; i < outBankList.size(); i++)
		{
			inBankList.add(outBankList.get(i));
		}
		
		inBankList.remove(myBankTextView.getText().toString());
		
		if (inBankList.size() < 1)
		{
			String memo = "없음";
			inBankList.add(memo);
			myBankInView.setClickable(false);
			myBankInView.setTag(false);
		}
		else
		{
			myBankInView.setClickable(true);
			myBankInView.setTag(true);
		}
		
		if (myBankInTextView.getText().toString().equals("")
				|| myBankInTextView.getText().toString().equals(myBankTextView.getText().toString()))
		{
			myBankInTextView.setText(inBankList.get(0).toString());
		}
	}
	
	private void setFilterCreditData()
	{
		inBankList.clear();
		
		for (int i = 0; i < outBankList.size(); i++)
		{
			inBankList.add(outBankList.get(i));
		}
		
		if (inBankList.size() < 1)
		{
			String memo = "없음";
			inBankList.add(memo);
			myBankInView.setClickable(false);
			myBankInView.setTag(false);
		}
		else
		{
			myBankInView.setClickable(true);
			myBankInView.setTag(true);
		}
		
		myBankInTextView.setText(inBankList.get(0).toString());
	}
	
	private void setBalanceInBank()
	{
		sql.selectMapTile(InsertMyBankActivity.this, "SELECT money FROM bankbook WHERE name = '" 
				+ BDUtil.getApostrophe(myBankInTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("money");
				c.moveToFirst();
	//			int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
	//				money = money + Integer.parseInt(c.getString(columIndex));
					money = money.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				inBalanceTextView.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	private void setBalanceCredit()
	{
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(myCreditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("outmoney");
				c.moveToFirst();
//				int outmoney = 0;
				BigDecimal outmoney = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
//					outmoney = outmoney + Integer.parseInt(c.getString(columIndex));
					outmoney = outmoney.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				outBalanceTitle.setText("카드대금");
				outBalanceTextView.setText(BDUtil.getWon(outmoney.toString()) + shape);
			}
		});
	}
	
	private void setBalanceOutBank()
	{
		sql.selectMapTile(InsertMyBankActivity.this, "SELECT money FROM bankbook WHERE name = '" 
				+ BDUtil.getApostrophe(myBankTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("money");
				c.moveToFirst();
	//			int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
	//				money = money + Integer.parseInt(c.getString(columIndex));
					money = money.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				outBalanceTitle.setText("잔액");
				outBalanceTextView.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Activity.RESULT_OK)
		{
			switch (requestCode)
			{
				case REQUEST_OUT_BANK:
				{
					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
					myBankTextView.setText(selectData);
					
					setBalanceOutBank();
					setFilterBankData();
					setBalanceInBank();
					break;
				}
				case REQUEST_OUT_CREDIT:
				{
					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
					myCreditTextView.setText(selectData);
					
					setBalanceCredit();
					break;
				}
				case REQUEST_IN_BANK:
				{
					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
					myBankInTextView.setText(selectData);
					
					setBalanceInBank();
					break;
				}
//				case REQUEST_OUT_CATEGORY:
//				{
//					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
//					categoryOutTextView.setText(selectData);
//					break;
//				}
				case REQUEST_IN_CATEGORY:
				{
					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
					categoryInTextView.setText(selectData);
					break;
				}
				case REQUEST_AUTO_DATE:
				{
					String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
					dateTextView.setText(selectData);
					break;
				}
			}
		}
		else if (resultCode == RadioDialogActivity.REFRESH_CATEGORY)
		{
//			if (requestCode == REQUEST_OUT_CATEGORY)
//			{
//				final String beforeOutCategory = categoryOutTextView.getText().toString();
//				
//				sql.selectMapTile(this, "SELECT kind FROM category_move_list ORDER BY count DESC", new ParseSelectData()
//				{
//					@Override
//					public void resultData(Cursor c)
//					{
//						categoryOutList = new ArrayList<String>();
//						
//						int nameIndex = c.getColumnIndex("kind");
//						c.moveToFirst();
//						
//						for (int i = 0; i < c.getCount(); i++)
//						{
//							String kind = c.getString(nameIndex);
//							categoryOutList.add(kind);
//							c.moveToNext();
//						}
//						
//						if (categoryInList.size() < 1)
//						{
//							String memo = "없음";
//							categoryOutList.add(memo);
//							categoryOutView.setClickable(false);
//						}
//						
//						categoryOutTextView.setText(beforeOutCategory);
//					}
//				});
//			}
			if (requestCode == REQUEST_IN_CATEGORY)
			{
				final String beforeInCategory = categoryInTextView.getText().toString();
				
				sql.selectMapTile(this, "SELECT kind FROM category_move_list ORDER BY count DESC", new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						categoryInList = new ArrayList<String>();
						
						int nameIndex = c.getColumnIndex("kind");
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							String kind = c.getString(nameIndex);
							categoryInList.add(kind);
							c.moveToNext();
						}
						
						if (categoryInList.size() < 1)
						{
							String memo = "없음";
							categoryInList.add(memo);
							categoryInView.setClickable(false);
						}
						
						categoryInTextView.setText(beforeInCategory);
					}
				});
			}
		}
	}
	
	/**
	 * 데이터를 인서트 한다.
	 */
	private void setInsertData() throws Exception
	{
		if (flag == 1)
		{
			setAutoMyBankData();
		}
		else if (flag == 0)
		{
			setAutoMyBankUpdate();
		}
		else
		{
			BalanceQuery balace = new BalanceQuery(superContext);
			
			if (bankRadio.isChecked())
			{
				setOutData(myBankTextView.getText().toString(), BDConstents.BANK_TYPE);
				setOutBankData(BDUtil.getCommaDel(money.getText().toString()));
				
				// 잔액을 입력한다.
				balace.setBalance(BDConstents.BANK_TYPE, myBankTextView.getText().toString());
				
				setSusuData(myBankTextView.getText().toString(), BDConstents.BANK_TYPE);
			}
			else if (creditRadio.isChecked())
			{
				setOutData(myCreditTextView.getText().toString(), BDConstents.CREDIT_TYPE);
				setOutCreditData(BDUtil.getCommaDel(money.getText().toString()));
				
				// 잔액을 입력한다.
				balace.setBalance(BDConstents.CREDIT_TYPE, myCreditTextView.getText().toString());
				
				setSusuData(myCreditTextView.getText().toString(), BDConstents.CREDIT_TYPE);
			}
			
			setInData();
			setInBankData();
			
			if (setLinkId() == false)
			{
				throw new Exception();
			};
			
			// 내통장이체로 돈이 입금되는 곳의 잔액을 입력한다.
			balace.setBalance(BDConstents.BANK_TYPE, myBankInTextView.getText().toString());
		}
		
		// 카테고리 카운트 하나 증가
		sql.selectMapTile(this, "SELECT count FROM category_move_list WHERE kind = '" +
				BDUtil.getApostrophe(categoryInTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int countIndex = c.getColumnIndex("count");
				int count = 0;
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					count = c.getInt(countIndex);
					c.moveToNext();
				}
				
				count++;
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("count", "" + count);
				String [] whereArgs = new String[]{categoryInTextView.getText().toString()};
				sql.update(superContext, "category_move_list", map, "kind = ?", whereArgs);
			}
		});
	}

	/**
	 * 내통장 자동이체 테이블을 수정한다.
	 */
	private void setAutoMyBankUpdate()
	{
		Intent intent = getIntent();
		MyBankAutoData data = intent.getParcelableExtra(MyBankAutoActivity.AUTO_DATA);
		
		HashMap<String, String> map	= new HashMap<String, String>();
		
		if (bankRadio.isChecked())
		{
			map.put("kind", "" + 1);
			map.put("outkind", myBankTextView.getText().toString());
		}
		else if (creditRadio.isChecked())
		{
			map.put("kind", "" + 2);
			map.put("outkind", myCreditTextView.getText().toString());
		}
		
		map.put("inkind", myBankInTextView.getText().toString());
		
		map.put("name", autoNameEditText.getText().toString());
//		map.put("autodate", dateTextView.getText().toString());
		map.put("autodate", toDay + "");
		
//		Calendar cal = Calendar.getInstance();
//		
//		int year = cal.get(Calendar.YEAR);
//		
//		int month = cal.get(Calendar.MONTH)+1;
//		int day = Integer.parseInt(dateTextView.getText().toString());
//		map.put("signdate", BDUtil.getDateDB(year, month, day));
		
		Calendar cal = Calendar.getInstance();
		cal.set(toYear, toMonth, toDay);
		cal.add(Calendar.MONTH, -1);
		
		map.put("signdate", BDUtil.getDateDB(
				cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
		
		map.put("outcategory", categoryInTextView.getText().toString());
		map.put("incategory", categoryInTextView.getText().toString());
		
		map.put("money", BDUtil.getCommaDel(money.getText().toString()));
		
		if (BDUtil.getCommaDel(susuMoney.getText().toString()).length() > 0)
		{
			map.put("susumoney", BDUtil.getCommaDel(susuMoney.getText().toString()));
		}
		
		map.put("memo", memoEditText.getText().toString());
		
		String [] whereArgs = new String[]{data.getId() + ""};
		sql.update(this, "auto_mybank", map, "id = ?", whereArgs);
	}

	/**
	 * 내통장 자동이체 테이블에 데이터를 넣는다.
	 */
	private void setAutoMyBankData()
	{
		HashMap<String, String> map	= new HashMap<String, String>();
		
		if (bankRadio.isChecked())
		{
			map.put("kind", "" + 1);
			map.put("outkind", myBankTextView.getText().toString());
		}
		else if (creditRadio.isChecked())
		{
			map.put("kind", "" + 2);
			map.put("outkind", myCreditTextView.getText().toString());
		}
		
		map.put("inkind", myBankInTextView.getText().toString());
		
		map.put("name", autoNameEditText.getText().toString());
		map.put("autodate", toDay + "");
		
//		Calendar cal = Calendar.getInstance();
//		
//		int year = cal.get(Calendar.YEAR);
//		
//		// 이줄은 테스트때문에 넣음.
////		int month = cal.get(Calendar.MONTH)-1;
//		
//		int month = cal.get(Calendar.MONTH)+1;
//		int day = Integer.parseInt(dateTextView.getText().toString());
//		
//		if (day >= cal.get(Calendar.DAY_OF_MONTH))
//		{
//			if (month == 1)
//			{
//				year--;
//				month = 12;
//			}
//			else 
//			{
//				month--;
//			}
//		}
		
		Calendar cal = Calendar.getInstance();
		cal.set(toYear, toMonth, toDay);
		cal.add(Calendar.MONTH, -1);
		
		map.put("signdate", BDUtil.getDateDB(
				cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
		
		map.put("outcategory", categoryInTextView.getText().toString());
		map.put("incategory", categoryInTextView.getText().toString());
		
		map.put("money", BDUtil.getCommaDel(money.getText().toString()));
		
		if (BDUtil.getCommaDel(susuMoney.getText().toString()).length() > 0)
		{
			map.put("susumoney", BDUtil.getCommaDel(susuMoney.getText().toString()));
		}
		
		map.put("memo", memoEditText.getText().toString());
		
		sql.insert(this, map, "auto_mybank");
	}

	private void setInBankData()
	{
		sql.selectMapTile(this, "SELECT money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(myBankInTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
//				int tempMoney = Integer.parseInt(money.getText().toString());
				
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.add(tempMoney);
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				String [] whereArgs = new String[]{myBankInTextView.getText().toString()};
				sql.update(InsertMyBankActivity.this, "bankbook", map, "name = ?", whereArgs);
			}
		});
	}

	private boolean setLinkId()
	{
		if (linkId < 0)
		{
			return false;
		}
		
		if (inoutLinkId < 0)
		{
			return false;
		}
		
		HashMap<String, String> map1 = new HashMap<String, String>();
		map1.put("linkid", linkId + "");
		String [] whereArgs1 = new String[]{inoutLinkId + ""};
		sql.update(InsertMyBankActivity.this, "in_out", map1, "id = ?", whereArgs1);
		
		HashMap<String, String> map2 = new HashMap<String, String>();
		map2.put("linkid", inoutLinkId + "");
		String [] whereArgs2 = new String[]{linkId + ""};
		sql.update(InsertMyBankActivity.this, "in_out", map2, "id = ?", whereArgs2);
		
		return true;
	}

	private void setSusuData(String moneykind, String linktype)
	{
		if (BDUtil.getCommaDel(susuMoney.getText().toString()).length() < 1 
				|| BDUtil.getCommaDel(susuMoney.getText().toString()).equals("0"))
		{
			return;
		}
		
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", BDConstents.CATEGORY_SUSUMONEY);
		map.put("type", BDConstents.MYBANK_INOUT_TYPE);
		
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		map.put("date", date);
		map.put("moneykind", moneykind);
		
		if (linktype.equals(BDConstents.CREDIT_TYPE))
		{
			map.put("postmoney", BDUtil.getCommaDel(susuMoney.getText().toString()));
		}
		else
		{
			map.put("outmoney", BDUtil.getCommaDel(susuMoney.getText().toString()));
		}
		
		map.put("linktype", linktype);
		
		map.put("memo", memoEditText.getText().toString());
		
		sql.insert(this, map, "in_out");
		
		if (linktype.equals(BDConstents.BANK_TYPE))
		{
			setOutBankData(BDUtil.getCommaDel(susuMoney.getText().toString()));
		}
		else if (linktype.equals(BDConstents.CREDIT_TYPE))
		{
			setOutCreditData(BDUtil.getCommaDel(susuMoney.getText().toString()));
		}
		
		sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIndex = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				int id = -1;
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIndex);
					c.moveToNext();
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("linkid", inoutLinkId + "");
				String [] whereArgs = new String[]{id + ""};
				sql.update(InsertMyBankActivity.this, "in_out", map, "id = ?", whereArgs);
			}
		});
		
		// 수수료 입력후 잔액을 입력한다.
		BalanceQuery balace = new BalanceQuery(superContext);
		balace.setBalance(linktype, moneykind);
	}

	private void setInData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", categoryInTextView.getText().toString());
		map.put("type", BDConstents.MYBANK_INOUT_TYPE);
		
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		map.put("date", date);
		map.put("moneykind", myBankInTextView.getText().toString());
		map.put("inmoney", BDUtil.getCommaDel(money.getText().toString()));
		map.put("linktype", BDConstents.BANK_TYPE);
		
		map.put("memo", memoEditText.getText().toString());
		
		sql.insert(this, map, "in_out");
		
		sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIndex = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				linkId = -1;
				for (int i = 0; i < c.getCount(); i++)
				{
					linkId = c.getInt(idIndex);
					c.moveToNext();
				}
			}
		});
	}

	private void setOutBankData(final String money)
	{
		sql.selectMapTile(this, "SELECT money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(myBankTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money));
//				int tempMoney = Integer.parseInt(money.getText().toString());
				
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.subtract(tempMoney);
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				String [] whereArgs = new String[]{myBankTextView.getText().toString()};
				sql.update(InsertMyBankActivity.this, "bankbook", map, "name = ?", whereArgs);
			}
		});
	}
	
	private void setOutCreditData(final String money)
	{
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(myCreditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(money);
				int moneyIndex = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) + tempMoney;
					money = money.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				money = money.add(tempMoney);
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				String [] whereArgs = new String[]{myCreditTextView.getText().toString()};
				sql.update(InsertMyBankActivity.this, "credit_card", map, "name = ?", whereArgs);
			}
		});
	}

	private void setOutData(String moneyKind, String linkType)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", categoryInTextView.getText().toString());
		map.put("type", BDConstents.MYBANK_INOUT_TYPE);
		
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		map.put("date", date);
		map.put("moneykind", moneyKind);
		
		if (linkType.equals(BDConstents.BANK_TYPE))
		{
			map.put("outmoney", BDUtil.getCommaDel(money.getText().toString()));
		}
		else if (linkType.equals(BDConstents.CREDIT_TYPE))
		{
			map.put("postmoney", BDUtil.getCommaDel(money.getText().toString()));
		}
		
		map.put("linktype", linkType);
		
		map.put("memo", memoEditText.getText().toString());
		
		sql.insert(this, map, "in_out");
		
		sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIndex = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				inoutLinkId = -1;
				for (int i = 0; i < c.getCount(); i++)
				{
					inoutLinkId = c.getInt(idIndex);
					c.moveToNext();
				}
			}
		});
	}

	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(InsertMyBankActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				try
				{
					sql.beginTansaction(superContext);
					
					setInsertData();
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) 
					{
						return -1;
					}
				}
			}
			else
			{
				return arg0[0];
			}
			
			return arg0[0];
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0) 
			{
				if (flag == 1)
				{
//					Calendar cal = Calendar.getInstance();
//					int day = Integer.parseInt(dateTextView.getText().toString());
//					
//					if (day == cal.get(Calendar.DAY_OF_MONTH))
//					{
//						setResult(Activity.RESULT_OK);
//					}
					
					setResult(Activity.RESULT_OK);
				}
				
				BDUtil.showDialogFinish(InsertMyBankActivity.this, "확인", "입력이 완료 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
